<?php

namespace YourApp\util;


/**
 * 解析头信息
 * Class MsgDecoder
 * @package YourApp\util
 */
class MsgDecoder{
    public function getPackageData($hex_string){

        $ret=new PackageData();

        //如果有分包就是16位,没有就是12位
        $msg_header=$this->parseMsgHeader($hex_string);
        $ret->MsgHeader=$msg_header;

        $msgBodyByteStartIndex = 12*2;

        //消息体
        if($msg_header->isHasSubPackage()){
            $msgBodyByteStartIndex=16*2;
        }
        $msg_body=substr($hex_string,$msgBodyByteStartIndex,$msg_header->msg_body_length*2);
        $ret->msg_body=$msg_body;

        //最后一位是校验码
        $check_sub_in_pkg=substr($hex_string,strlen($hex_string)-2,2);

        $calculated_check_sum=Common::calCheckSum(substr($hex_string,0,strlen($hex_string)-2));
        $ret->check_sum=$check_sub_in_pkg;

        if($calculated_check_sum!=$check_sub_in_pkg){
            throw new \Exception('错误,校验码不一致');
        }
        return $ret;
    }

    //解析头标识
    private function parseMsgHeader($hex_string){

        $msg_header=new MsgHeader();

        //消息id word(16) 2bytes
        $msg_header->msg_id=substr($hex_string,0,4);


        //消息体点属性 word(16) 2bytes
        // ----------------消息体属性 start--------------------------------------
        $msg_body_props=substr($hex_string,4,4);
        $msg_header->mgs_body_props_field=$msg_body_props;

        //转成10的整数
        $msg_body_props=hexdec($msg_body_props);
        //[0-9]消息体长度 0000,0011,1111,1111(3ff)
        $msg_header->msg_body_length=($msg_body_props & 0x3ff);
        //[10-12]加密类型 0001,1100,0000,0000(1c00)
        $msg_header->msg_encryption_type=(($msg_body_props & 0x1c00)>>10);
        //[13] 是否有子包 0010,0000,0000,0000(2000)(是否有子包)
        $msg_header->has_sub_package=(($msg_body_props & 0x2000)>>13);
        //[14-15] 保留为 1100,0000,0000,0000(C000)
        $msg_header->reserved_bit=(($msg_body_props & 0xc000)>>14);
        //-----------------------消息体属性 end------------------------------------------------

        //终端手机号,因为只有0-9 所以直接就可以使用
        $msg_header->terminal_phone=substr($hex_string, 8, 12);

        //信息流水号
        $msg_header->flow_id=hexdec(substr($hex_string, 20, 4));

        //信息包封装项
        if($msg_header->isHasSubPackage()){
            // 消息包封装项字段
            $msg_header->package_info_filed=substr($hex_string, 24, 8);
            $msg_header->total_sub_package=hexdec(substr($hex_string, 24, 4));
            $msg_header->sub_package_seq=hexdec(substr($hex_string, 28, 4));
        }
        return $msg_header;
    }

}
